package org.example.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.exception.ServiceException;
import org.example.system.entity.BlockEntity;
import org.example.system.mapper.BlockMapper;
import org.example.system.service.BlockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 板块服务实现
 */
@Service
public class BlockServiceImpl implements BlockService {
    @Autowired
    private BlockMapper blockMapper;
    
    /**
     * 按条件分页查询
     * @param block
     * @return
     */
    @Override
    public IPage<BlockEntity> selectPage(BlockEntity block){
        LambdaQueryWrapper<BlockEntity> wrapper = new LambdaQueryWrapper<>();
        IPage<BlockEntity> page = new Page<>();
        page.setCurrent(block.getPageNum());
        page.setSize(block.getPageSize());
        return blockMapper.selectPage(page,wrapper);
    }

    /**
     * 添加板块
     * @param block
     * @return
     */
    @Override
    public int add(BlockEntity block) {
        //用相同的板块名去查数据库
        LambdaQueryWrapper<BlockEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BlockEntity::getBlockName,block.getBlockName());   //相同的blockname
        List<BlockEntity> existList = blockMapper.selectList(wrapper);
        //如果存在抛出一个自定义异常
        if(null != existList && existList.size() > 0){//证明存在板块名相同的板块名
            throw new ServiceException("板块名已存在");
        }
        block.setCreateTime(new Date());
        return blockMapper.insert(block);
    }

    /**
     * 修改
     * @param block
     * @return
     */
    @Override
    public int update(BlockEntity block) {
        //用相同的板块名去查数据库
        LambdaQueryWrapper<BlockEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BlockEntity::getBlockName,block.getBlockName());
        List<BlockEntity> existList = blockMapper.selectList(wrapper);
        //如果存在抛出一个自定义异常
        if(null != existList && existList.size() > 0){//证明存在板块名相同的板块名
            BlockEntity existBlock = existList.get(0);
            if (!existBlock.getId().equals(block.getId())) {
                throw new ServiceException("板块名已存在");
            }
        }
        block.setUpdateTime(new Date());
        return blockMapper.updateById(block);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(Long[] ids) {
        return blockMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 根据id获取信息
     *
     * @param id
     * @return
     */
    @Override
    public BlockEntity getOne(Long id) {
        return blockMapper.selectById(id);
    }
}
